#!/bin/sh
#export PCACHE="$HOME/.cache/vifm/thumbnail.$(stat --printf '%n\0%i\0%F\0%s\0%W\0%Y' -- "$(readlink -f "$PWD/$6")" | sha256sum | awk '{print $1}')"
export PCACHE="$HOME/.cache/vifm/thumbnail.$(stat --printf '%n\0%i\0%F\0%s\0%W\0%Y' -- "$(readlink -f "$PWD/$6")"  | awk '{print $1}')"

pclear() {
	printf '{"action": "remove", "identifier": "vifm-preview"}\n' > "$FIFO_UEBERZUG"
}

image() {
		#echo  "$2" "$3" "$4" "$5" "$6"
		
		#chafa "$6" -s "$4x"

		# timg -g 30x30 test.png
		#timg -g "$(($2-1))"x"$(($3-1))"@"$4"x"$5" "$6"
		#timg -g "$(($2-1))"x"$(($3-1))" "$6"
		# timg   -g 30x30 "$6"
		timg   -g "$4"x"$5" "$6"

		# kitty +kitten icat --clear
		# # kitty +kitten icat --place 10x10@0x0 test.png
		# kitty +kitten icat --place "$2"x"$3"@"$4"x"$5" "$6"
		
		# sleep 3s
		# kitty +kitten icat --clear
		exiftool -a -u -g1 "$6"
		exit 1
	# fi
}

main() {
    case "$1" in
        "clear")
			pclear "$@"
			;;
        "draw")
			FILE="$PWD/$6"
			image "$1" "$2" "$3" "$4" "$5" "$FILE"
			;;
        "video")
			[ ! -f "$PCACHE" ] && \
				ffmpegthumbnailer -i "$6" -o "${PCACHE}.jpg" -s 0 -q 5
			image "$1" "$2" "$3" "$4" "$5" "${PCACHE}.jpg"
			;;
        "epub")
			[ ! -f "$PCACHE" ] && \
				epub-thumbnailer "$6" "$PCACHE" 1024
			image "$1" "$2" "$3" "$4" "$5" "$PCACHE"
			;;
        "pdf")
			[ ! -f "${PCACHE}.jpg" ] && \
				pdftoppm -jpeg -f 1 -singlefile "$6" "$PCACHE"
			image "$1" "$2" "$3" "$4" "$5" "${PCACHE}.jpg"
			;;
        "djvu")
			[ ! -f "${PCACHE}.jpg" ] && \
				ddjvu -format=tiff -quality=90 -page=1 "$6" "$PCACHE.jpg"
			image "$1" "$2" "$3" "$4" "$5" "${PCACHE}.jpg"
			;;
        "audio")
			[ ! -f "${PCACHE}.jpg" ] && \
				ffmpeg -hide_banner -i "$6" "${PCACHE}.jpg" -y >/dev/null
			image "$1" "$2" "$3" "$4" "$5" "${PCACHE}.jpg"
			;;
        "font")
			[ ! -f "${PCACHE}.jpg" ] && \
				fontpreview -i "$6" -o "${PCACHE}.jpg"
			image "$1" "$2" "$3" "$4" "$5" "${PCACHE}.jpg"
			;;
        *)
    esac
}
main "$@"
